package com.homework.servlet.admin;

import com.google.gson.Gson;
import com.homework.entity.User;
import com.homework.factory.ServiceFactory;
import com.homework.service.UserService;
import com.homework.servlet.BaseServlet;
import com.homework.util.GudgeType;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/admin/user.do")
public class UserMenegerServlet extends BaseServlet {

    UserService userService= ServiceFactory.getUserService();

    public void showAllUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> users = userService.showAllUser();
        Gson gson = new Gson();
        String s = gson.toJson(users);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(s);
    }


    protected void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User user = userService.queryUserById(Integer.parseInt(id));
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (GudgeType.isNull(user)){
            writer.write(new Gson().toJson(0));
        }else {

        }
    }

    protected void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User user = userService.queryUserById(Integer.parseInt(id));
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (GudgeType.isNull(user)){
            writer.write(new Gson().toJson(0));
            return;
        }
        int i = userService.deleteUser(Integer.parseInt(id));
        if (i<=0){
            writer.write(new Gson().toJson(0));
        }else {
            writer.write(new Gson().toJson(1));
        }
    }
}
